#!/usr/bin/env python
# -*- encoding: utf-8 -*-
'''
@File    :   app.py
@Time    :   2021/08/29 16:29:57
@Author  :   Dillon
@Version :   1.0
@Contact :   aa269440877@outlook.com
@License :   GNU General Public License v3.0
@Desc    :   None
@WebSite :   None
'''

# here put the import lib
import os
from flask import Flask, render_template, request
from flask_socketio import SocketIO, disconnect
from logger import logger

app = Flask(__name__)
app.config['SECRET_KEY'] = 'vnkdjnfjknfl1232#'
socketio = SocketIO(app)


@app.route('/CSS_properties_and_alues', methods=['GET', 'POST'])
def CSS_properties_and_alues():
    title = 'CSS_properties_and_alues'
    logger.info(title)
    try:
        return render_template(title + ".html", title=title)
    except Exception as e:
        return str(e)


@app.route("/")
@app.route("/base")
def base():
    title = 'base'
    logger.info(os.getcwd())
    templates_path = os.path.join("./app/templates")
    base_html = os.path.join("./app/templates/base.html")
    with open(base_html, encoding="utf8") as f:
        base_content = f.readlines()

    for line in base_content:

        if "{% block content %}" in line:
            logger.info(base_content.index(line))
            block_line_number = base_content.index(line)
        if "{% endblock content %}" in line:
            logger.info(base_content.index(line))
            endblock_line_number = base_content.index(line)

    item_headers = list()
    items = os.listdir(templates_path)
    for item in items:
        item_name = item.split(".")[0]
        item_headers.append(
            f'''            <a href="{item_name}" target="_blank"><h1>\
            {item_name}</h1></a>\n''')

    base_content = base_content[:block_line_number + 1] + item_headers + \
        base_content[endblock_line_number:]
    with open(base_html, "w", encoding="utf8") as f:
        f.writelines(base_content)

    try:
        return render_template(title + ".html", title=title)
    except Exception as e:
        return str(e)


@app.route("/flex", methods=['GET', 'POST'])
def flex():
    title = 'flex'
    logger.info(title)
    try:
        return render_template(title + '.html', title=title)
    except Exception as e:
        return str(e)


@app.route("/grid", methods=["GET", "POST"])
def grid():
    title = 'grid'
    try:
        return render_template(title + ".html", title=title)
    except Exception as e:
        return str(e)


@app.route("/dynamic_toc", methods=["GET", "POST"])
def dynamic_toc():
    title = 'dynamic_toc'
    try:
        return render_template(title + ".html", title=title)
    except Exception as e:
        return str(e)


@app.route("/shapes_layout", methods=["GET", "POST"])
def shapes_layout():
    title = 'shapes_layout'
    try:
        return render_template(title + ".html", title=title)
    except Exception as e:
        return str(e)


@app.route("/javascript", methods=["GET", "POST"])
def javascript():
    title = 'javascript'
    try:
        return render_template(title + ".html", title=title)
    except Exception as e:
        return str(e)


# ************  socketio event start  ************
# listening: default event
@socketio.on('connect')
def connect_default_event():
    logger.info('client: connect')
    socketio.send('client: connect')


# 服务连接后一直在print message
# @socketio.on('message')
# def message_default_event(message):
#     logger.info(message)
#     socketio.send('client:' + message)

@socketio.on('json')
def json_default_event(json):
    logger.info(json)
    socketio.send('client:' + str(json))


@socketio.on('disconnect')
def disconnect_default_event():
    logger.info('client: disconnect')
    socketio.send('client: disconnect')


# listening: custom event
def messageReceived(methods=['GET', 'POST']):
    logger.info('message was received!!!')


@socketio.on('my event')
def handle_my_custom_event(json, methods=['GET', 'POST']):
    logger.info('received my event: ' + str(json))
    socketio.emit('my response', json, callback=messageReceived)
    logger.info('json', json)
    # json {'data': 'User Connected'}
    # json {'user_name': '1', 'message': ''}
    if 'message' in json and json['message'] == 'disconnect':
        # to disconnect connect
        disconnect()

# ************  socketio event end  ************

# ************  upload file(s) start  ************


@app.route('/upload_conf_file', methods=['POST'])
def upload_conf_file():
    file = request.files['file']
    if file:
        # filename = secure_filename(file.filename)
        filename = file.filename
        confs_folder = os.path.join('app\\tool\\CreateHPMImage\\SampleConf')
        file.save(os.path.join(confs_folder, filename))
        return "Uploaded {0} to server, connect administrator to restart\
            server then it will be appended to conf list.\n".format(filename)


@app.route('/uploadFile', methods=["GET", "POST"])
def uploadFile():
    # send_from_html = request.form.get('send_from_html', '')
    # logger.info(send_from_html

    if request.method == 'POST':
        logger.info('\n')
        # get form data
        mode_name = 'name'
        mode_name = request.form.get(mode_name)

        # excep_path field type(multiple) is file  in output mode
        excel_path_name = 'name'
        uploaded_files = request.files.getlist(excel_path_name)
        excel_path = list()
        for file in uploaded_files:
            if file:
                # filename = secure_filename(file.filename)
                filename = file.filename
                excel_path.append(filename)
                file.save(os.path.join('insert_folder', filename))


# ************  upload file(s) end  ************


if __name__ == '__main__':
    host = os.environ.get('IP', '127.0.0.1')
    port = int(os.environ.get('PORT', 6001))
    # app.run(host=host, port=port, threaded=True)
    socketio.run(app, host=host, port=port, debug=True)
